/**
 * 阿里云短信服务[SMS]
 * 文档：https://next.api.aliyun.com/document/Dysmsapi/2017-05-25/SendSms
 */
import SMSClient from "@alicloud/sms-sdk"
import { writeLog, isEmpty } from "../../utils/utils"

// 阿里云SMS模板id
const SMSCode = {
  VIP_REGISTER: 'SMS_255200957', // 会员注册
  VIP_RECHARGE: 'SMS_255230915', // 会员充值
  VIP_PAYMENT: 'SMS_255355926' // 会员结账
}

const handleSMS = (opts) => {
  return new Promise((resolve, reject) => {
    //初始化sms_client
    let smsClient = new SMSClient({
      accessKeyId: 'xxx',  //AccessKey ID
      secretAccessKey: 'xxx'  // AccessKey Secret
    })

    const { phone, codeKey, templateParam } = opts || {}
    try {
      if (isEmpty(phone)) {
        // reject({ code: -1, msg: '请传入手机号码' })
        throw '[参数错误]请传入手机号码'
      }
      if (isEmpty(codeKey)) {
        // reject && reject({ code: -1, msg: '请传入SMS模板id字典名称' })
        throw '[参数错误]请传入SMS模板id字典名称'
      }


      // 开始发送短信
      smsClient.sendSMS({
        PhoneNumbers: phone,
        SignName: "新星台球", //签名名称
        TemplateCode: SMSCode[codeKey], //模版CODE
        TemplateParam: templateParam, // 短信模板变量对应的实际值，JSON格式
      }).then(result => {
        let { Code } = result
        if (Code == 'OK') {
          resolve({ code: 1, msg: '发送成功', ...result })
        }
      }).catch(err => {
        let errorTxt = JSON.stringify(err.data)
        // writeLog("[SMS error]" + errorTxt)
        // reject({ code: -1, msg: '发送失败', ...err.data })
        throw '[SMS error 发送失败]' + errorTxt
      })
    } catch (error) {
      writeLog(error)
    }
  })
}

export default handleSMS